using Engine;
using Game;
using GameEntitySystem;

namespace SCIENEW {
    public class TrainItemBehavior : ItemBehavior {
        public TrainItemBehavior(Project project) : base(project) { }

        public override bool OnUse(Ray3 ray, ComponentMiner componentMiner) {
            int activeBlockValue = componentMiner.ActiveBlockValue;
            TerrainRaycastResult? result = componentMiner.Raycast<TerrainRaycastResult>(ray, RaycastMode.Digging);
            Entity entity;
            Vector3 position;
            if (result.HasValue) {
                if ((activeBlockValue == ItemsBlockManager.IdMap["Train"] || activeBlockValue == ItemsBlockManager.IdMap["Minecart"] || activeBlockValue == ItemsBlockManager.IdMap["ETrain"])
                    && result.HasValue
                    && Terrain.ExtractContents(result.Value.Value) == RailBlock.Index) {

					position = new Vector3(result.Value.CellFace.Point) + new Vector3(0.5f);
					entity = DatabaseManager.CreateEntity(Project, activeBlockValue == ItemsBlockManager.IdMap["Minecart"] ? "Carriage" : activeBlockValue == ItemsBlockManager.IdMap["Train"] ? "Train" : "ETrain", true);

					var rotation = componentMiner.ComponentCreature.ComponentCreatureModel.EyeRotation.GetForwardVector();
					entity.FindComponent<ComponentTrain>(true).SetDirection(RailBlock.IsDirectionX(RailBlock.GetRailType(Terrain.ExtractData(result.Value.Value)))
						? rotation.Z < 0 ? 0 : 2
						: rotation.X < 0 ? 1 : 3);
					entity.FindComponent<ComponentBody>(true).Position = position;
					entity.FindComponent<ComponentSpawn>(true).SpawnDuration = 0f;
					Project.AddEntity(entity);
					var componentTrain = entity.FindComponent<ComponentTrain>(true);
					if (activeBlockValue == ItemsBlockManager.IdMap["Minecart"])
					{
						componentTrain.Update(0);
						var train = componentTrain.FindNearestTrain();
						if (train != null)
							componentTrain.ParentBody = train;
					}
					componentMiner.RemoveActiveTool(1);
					return true;
                }
            }
			return false;

        }
    }
}